<?php


namespace PKApp\Tools;

use PKCore\Request;

class CaptchaCode
{

    public function Main()
    {
        //imagecreatetruecolor函数建一个真彩色图像
        $image = imagecreatetruecolor(100, 30);
        //生成彩色像素
        //白色背景 imagecolorallocate 函数为一幅图像分配颜色
        $bgColor = imagecolorallocate($image, 255, 255, 255);
        //蓝色文本
        $textcolor = imagecolorallocate($image, 0, 0, 255);
        //填充函数，xy确定坐标，color颜色执行区域填充颜色
        imagefill($image, 0, 0, $bgColor);
        //初始空值
        $captchaCode = '';
        //该循环,循环取数
        for ($i = 0; $i < 4; $i++) {
            $fontsize = 6;
            $x = ($i * 25) + rand(5, 10);
            //位置随机
            $y = rand(5, 10);
            $fontContent = \PKCore\randstr(1);
            //随机的rgb()值可以自己定
            $fontcolor = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
            //水平地画一行字符串
            imagestring($image, $fontsize, $x, $y, $fontContent, $fontcolor);
            $captchaCode .= $fontContent;
        }
        \request()->cookie('authCode', $captchaCode, CAPTCHA_CODE_EXPIRE);
        //该循环,循环画背景干扰的点
        for ($m = 0; $m <= 600; $m++) {
            $x2 = rand(1, 99);
            $y2 = rand(1, 99);
            $pointColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            // 水平地画一串像素点
            imagesetpixel($image, $x2, $y2, $pointColor);
        }
        //该循环,循环画干扰直线
        for ($i = 0; $i <= 10; $i++) {
            $x1 = rand(0, 99);
            $y1 = rand(0, 99);
            $x2 = rand(0, 99);
            $y2 = rand(0, 99);
            $lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            //画一条线段
            imageline($image, $x1, $y1, $x2, $y2, $lineColor);

        }
        header('content-type:image/png');
        imagepng($image);
        //销毁
        imagedestroy($image);
        exit();
    }

}
